using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Configuration;
using System.Configuration;

/// <summary>
/// A page which allows changing of application settings.
/// </summary>
public partial class Settings : System.Web.UI.Page
{
    /// <summary>
    /// Populates the textboxes on the page with the current settings on first load.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void Page_Load(object sender, EventArgs e)
    {
        pnlError.Visible = false;
        if(!Page.IsPostBack) {
            radDBMode.DataSource = EnumBinder.EnumHelper.ToExtendedList<int>(typeof(Database.DatabaseType));
            radDBMode.DataTextField = "Value";
            radDBMode.DataValueField = "NumericKey";
            radDBMode.DataBind();

            radDBMode.SelectedValue = WebConfigurationManager.AppSettings["dbtype"];
            txtDBHost.Text = WebConfigurationManager.AppSettings["dbhost"];
            txtDBPort.Text = WebConfigurationManager.AppSettings["dbport"];
            txtDBUser.Text = WebConfigurationManager.AppSettings["dbuser"];
            txtDBPassword.Text = WebConfigurationManager.AppSettings["dbpass"];
            txtDBDatabase.Text = WebConfigurationManager.AppSettings["dbdatabase"];
        }
    }
    /// <summary>
    /// Tests and saves the configuration.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void btnSave_Click(object sender, EventArgs e) {
        System.Configuration.ConnectionStringSettings conn = null;
        System.Configuration.Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);
        Database db = new Database();
        try {
            Database.DatabaseType dbType = (Database.DatabaseType)Enum.Parse(typeof(Database.DatabaseType), radDBMode.SelectedValue);
            string connectionString = Database.GetConnectionString(dbType, txtDBHost.Text, int.Parse(txtDBPort.Text), txtDBUser.Text, txtDBPassword.Text, txtDBDatabase.Text);
            db.OpenConnection(dbType, connectionString); 
            KeyValueConfigurationCollection appSettings = config.AppSettings.Settings;
            appSettings["dbtype"].Value = radDBMode.SelectedValue;
            appSettings["dbhost"].Value = txtDBHost.Text;
            appSettings["dbport"].Value = txtDBPort.Text;
            appSettings["dbuser"].Value = txtDBUser.Text;
            appSettings["dbpass"].Value = txtDBPassword.Text;
            appSettings["dbdatabase"].Value = txtDBDatabase.Text;

            switch(radDBMode.SelectedIndex) {
                case 0:
                    conn = new System.Configuration.ConnectionStringSettings("Default", connectionString, "MySql.Data.MySqlClient");
                    break;
                case 1:
                    conn = new ConnectionStringSettings("Default", connectionString, "System.Data.SqlClient");
                    break;
            }
            if(config.ConnectionStrings.ConnectionStrings.IndexOf(conn) >= 0) {
                config.ConnectionStrings.ConnectionStrings.Remove("Default");
            }
            config.ConnectionStrings.ConnectionStrings.Add(conn);
            config.Save();
        } catch(System.Configuration.ConfigurationErrorsException cEx) {
            lblError.Text = "Error #401: Errorneous configuration - " + cEx.Message;
            pnlError.Visible = true;
        } catch(System.UnauthorizedAccessException uEx) {
            lblError.Text = "Error #402: The ASP.NET account must have access to the directory - "+uEx.Message;
            pnlError.Visible = true;
        } catch(InvalidOperationException iEx) {
            lblError.Text = "Error #403: " + iEx.Message;
            pnlError.Visible = true;
        } catch(MySql.Data.MySqlClient.MySqlException mEx) {
            lblError.Text = "Error #404: Could not connect to MySQL - " + mEx.Message;
            pnlError.Visible = true;
        } catch (Exception ex) {
            lblError.Text = "Error #405: Error saving connection settings - " + ex.Message;
            pnlError.Visible = true;
        }
    }

    /// <summary>
    /// Sets the default port when the SQL server type changes.
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void radDBMode_SelectedIndexChanged(object sender, EventArgs e) {
        switch(radDBMode.SelectedValue) {
            case "0":
                txtDBPort.Text = "3306";
                break;
            case "1":
                txtDBPort.Text = "1433";
                break;
        }
    }
}
